package com.ivan.action;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.ivan.beans.ChatUser;
import com.ivan.util.STRID;

public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = -7753479614757097566L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String userEmail = req.getParameter("email");
		String name = req.getParameter("username");
		System.out.println("name" + name + ", email:" + userEmail);
		UserService userService = UserServiceFactory.getUserService();
		System.out.println(userService.isUserLoggedIn());
		if(!userService.isUserLoggedIn()){
			String URL = userService.createLoginURL(req.getRequestURI());
			resp.sendRedirect(URL);
			return;
		} else {
			req.getSession().setAttribute("isInSession", "true");
			System.out.println("Attribute has been set...:" + name + ", mail:" + userEmail);
			String currentEmail = userService.getCurrentUser().getEmail();
			if(name != null && !"".equals(name) && 
					userEmail != null && currentEmail.equalsIgnoreCase(userEmail)){
				req.getSession().setAttribute("isInited", "true");
			}
		}
		
		if(userEmail != null && !"".equals(userEmail)){
			ChatUser user = new ChatUser();
			user.setEmail(userEmail);
			user.setName(name);
			Set<ChatUser> onlineUsers = null;
			ServletContext context = req.getSession().getServletContext(); 
			Object temp = context.getAttribute(STRID.ONLINE_USERS);
			if(temp != null){
				onlineUsers = (Set<ChatUser>)temp;
			} else {
				onlineUsers = new HashSet<ChatUser>();
			}
			onlineUsers.add(user);
			context.setAttribute(STRID.ONLINE_USERS, onlineUsers);
		}
		resp.sendRedirect("index.jsp");
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}	
	
	public static void main(String[] args){
		ChatUser a = new ChatUser();
		a.setEmail("a");
		ChatUser b = new ChatUser();
		b.setEmail("b");
		ChatUser c = new ChatUser();
		c.setEmail("c");
		ChatUser d = new ChatUser();
		d.setEmail("a");
		Set set = new HashSet();
		set.add(a);
		set.add(b);
		set.add(c);
		System.out.println(set.size());
		set.add(d);
		System.out.println(set.size());
	}
	
}
